﻿using System.Collections.Generic;

namespace Middleware
{
    public static class ObjectPooling
    {
        private static readonly IDictionary<int, List<RemoteObject>> Objects = new Dictionary<int, List<RemoteObject>>();
        private static int CountId { get; set; }

        public static int Add(RemoteObject o) {
            int id = GetNewId();
            Add(id, o);
            return id;
        }

        public static int GetNewId() {
            return CountId++;
        }

        public static void Add(int id, RemoteObject o) {
            if (!Objects.ContainsKey(id)) {
                Objects.Add(id, new List<RemoteObject>());
            }
            List<RemoteObject> list = Objects[id];
            list.Add(o);
        }

        public static object Get(int id) {
            if (!Objects.ContainsKey(id)) {
                return null;
            }
            List<RemoteObject> list = Objects[id];
            if (list.Count == 0) {
                return null;
            }
            RemoteObject o = list[0];
            list.Remove(o);
            list.Add(o);
            return o;
        }
    }
}
